const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
// 指定要存储或读取的文件路径
const filePath = __dirname + '/../data';
// 字符串下划线转驼峰
const formatToHump = (value) => {
  return value.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())
}

// 字符串驼峰转下划线
const formatToLine = (value) => {
  return value.replace(/([A-Z])/g, '_$1').toLowerCase()
}

/**
 * 数据对象key 驼峰下划线互相转化
 * @param {Object} data 需要转换的对象
 * @param {String} type hump-转驼峰 toLine-转下划线
 */
const formatHumpLineTransfer = (data, type = 'hump') => {
  let hump = ''
  // 转换对象中的每一个键值为驼峰的递归
  const formatTransferKey = (data) => {
    if (data instanceof Array) {
      data.forEach(item => formatTransferKey(item))
    } else if (data instanceof Object) {
      for (const key in data) {
        hump = type === 'hump' ? formatToHump(key) : formatToLine(key)
        data[hump] = data[key]
        if (key !== hump) {
          delete data[key]
        }
        if (data[hump] instanceof Object) {
          formatTransferKey(data[hump])
        }
      }
    } else if (typeof data === 'string') {
      data = type === 'hump' ? formatToHump(data) : formatToLine(data)
    }
  }
  formatTransferKey(data)
  return data
}


const stat = promisify(fs.stat);
const readdir = promisify(fs.readdir);

async function readDirInfo(tmpPath=filePath) {
    // 读path的路径是否为文件夹
    let info = await stat(tmpPath);

    // 保证外部给的路径是一个文件夹路径，才读读文件夹
    if (info.isDirectory()) {
      let map = {};
      // 是文件夹，就读文件夹
      let arr = await readdir(tmpPath);
      // 遍历
      let newArr = arr.map(item => {
        //promise
        return new Promise(async (resolve, reject) => {

          let fullPath = path.join(tmpPath, item);
          // 每一个子路径是否为文件
          let info = await stat(fullPath);
          if (info.isFile()) {
              // 是，保存文件路径
              // console.log(fullPath);
              resolve([item, true]);
            }
            else{
              // 不是，继续读下一级，递归
              let data = await readDirInfo(fullPath);
              resolve([item, data]);
            }
        });
      });

      let results = await Promise.all(newArr);
      results.forEach(([key, value]) => {
        map[key] = value;
      });
      return map;
    } 
    else{
      throw new Error("参数需要是一个文件夹路径");
    }
}
function saveJson(json, name) {
  
  // 使用fs.writeFile方法将文件内容写入指定路径
  return new Promise((resolve, reject) => {
    fs.writeFile(`${filePath}/${name}.json`, JSON.stringify(json), (err) => {
      if (err) {
        reject(err)
      } else {
        resolve('success')
      }
    })
  });
}
function getFileCon (name) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath + '/' + name, 'utf8', (err, data) => {  
      if (err) reject(err);  
      resolve(data)
    });
  })
}
module.exports = {
  formatToHump,
  saveJson,
  formatToLine,
  formatHumpLineTransfer,
  readDirInfo,
  getFileCon
}